package model

import (
	"cms/libs"
	"errors"
	"github.com/jinzhu/gorm"
	config "github.com/spf13/viper"
	"math"
)

type Link struct {
	gorm.Model
	Title string `gorm:"column:title" json:"title" form:"title" validate:"required"`
	Url   string `gorm:"column:url" json:"url" form:"url" validate:"required"`
	Sort  uint   `gorm:"column:sort" json:"sort" form:"sort"`
}

func (this *Link) List(page int) ([]Link, int, int) {
	var data = []Link{}
	var totalCount int
	db := libs.DB

	limit := config.GetInt("pagination.PageSize")
	offset := (page - 1) * limit
	db.Find(&data).Count(&totalCount)
	db.Offset(offset).Limit(limit).Order("id desc").Find(&data)
	totalPages := int(math.Ceil(float64(totalCount) / float64(limit)))
	return data, totalCount, totalPages
}

func (this *Link) SearchList(ids []string) []Link {
	var data = []Link{}
	db := libs.DB
	db.Where("id in (?)", ids).Order("id desc").Find(&data)
	return data
}

func (this *Link) ListAll() []Link {
	var data = []Link{}
	db := libs.DB
	db.Order("id desc").Find(&data)
	return data
}

func (this *Link) Info(id uint) (Link, error) {
	var link Link
	db := libs.DB

	if db.Where("id = ?", id).First(&link).RecordNotFound() {
		return Link{}, errors.New("内容未找到")
	}
	return link, nil
}

func (this *Link) Add(postValues map[string][]string) error {
	var link Link
	db := libs.DB

	if err := libs.FormDecode(&link, postValues); err != nil {
		return err
	}
	if err := libs.Validate(link); err != nil {
		return err
	}
	if !db.Where("title = ? ", link.Title).First(&Link{}).RecordNotFound() {
		return errors.New("该标题已经存在")
	}

	if err := db.Create(&link).Error; err != nil {
		return err
	}
	return nil
}

func (this *Link) Update(postValues map[string][]string) error {
	var link Link
	db := libs.DB

	if err := libs.FormDecode(&link, postValues); err != nil {
		return err
	}
	if err := libs.Validate(link); err != nil {
		return err
	}
	if !db.Where("title = ? and id != ?", link.Title, link.ID).First(&Link{}).RecordNotFound() {
		return errors.New("该标题已经存在")
	}
	if db.Where("id = ? ", link.ID).First(&Link{}).RecordNotFound() {
		return errors.New("未查询到内容id")
	}

	if err := db.Save(&link).Error; err != nil {
		return err
	}
	return nil
}

func (this *Link) Del(id uint) error {
	var link Link
	db := libs.DB

	if err := db.Where("id = ?", id).Delete(&link).Error; err != nil {
		return err
	}
	return nil
}
